package com.downbox.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 认证拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Value("${app.security.dev-mode:false}")
    private boolean devMode;

    @Value("${app.security.dev-token:}")
    private String devToken;

    @Value("${app.security.dev-uid:1}")
    private Long devUid;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 开发模式下直接跳过认证，设置默认用户ID
        if (devMode) {
            UserContext.setUserId(devUid);
            System.out.println("[开发模式] 跳过认证，自动设置用户ID: " + devUid);
            return true;
        }
        
        String token = request.getHeader("Authorization");

        // 生产模式，验证token
        if (token != null && token.startsWith("Bearer ")) {
            // 这里应该验证JWT token并提取用户ID
            // 暂时简化处理，假设token格式为 "Bearer token-uid-{userId}"
            String[] parts = token.substring(7).split("-");
            if (parts.length >= 3 && "uid".equals(parts[1])) {
                try {
                    Long userId = Long.parseLong(parts[2]);
                    UserContext.setUserId(userId);
                    return true;
                } catch (NumberFormatException e) {
                    // token格式错误
                }
            }
        }

        // 认证失败
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        response.getWriter().write("{\"code\":401001,\"message\":\"认证失败\",\"data\":null}");
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除用户上下文，避免内存泄漏
        UserContext.clear();
    }
}